const db = require('../config/db')

/**
 * 栏目列表接口逻辑
 */
exports.columnList = (req, res) => {
    // 获取前端的参数
    let { Search, page, size } = req.query
    page = (page - 1) * size
    let pageSql = 'select * from cms_column where del=0 '
    // 查询栏目总数的sql
    let totalSql = 'select count(*) as total from cms_column where del=0 '
    // 查询栏目列表sql
    if (Search == null) {
        pageSql = pageSql + 'limit ?, ?'
        argument = [Number(page), Number(size)]
    } else {
        pageSql = pageSql + ' and name like ? limit ?, ?'
        argument = ["%" + Search + "%", Number(page), Number(size)]
        totalSql = totalSql + " and name like ?"
    }
    db.query(pageSql, argument, (err, resPage) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        db.query(totalSql, "%" + Search + "%", (err, resTotal) => {
            if (err) {
                return res.send({ code: 1, message: err.message });
            }
            res.send({
                code: 0,
                data: {
                    list: resPage,
                    total: resTotal
                }
            })
        })
    })
}

/**
 * 栏目添加接口
 */
exports.addColumnList = (req, res) => {
    // 用户名或密码判空的校验
    let { name, orderby, type, content } = req.body;
    console.log(name, orderby, type);
    
    // 添加校验
    if (!name || !orderby || !type) {
        return res.send({ code: 1, message: '名字,排序,类型不能为空！' });
    };
    // 栏目信息插入数据库
    const userInsertSql = 'insert into cms_column (name, orderby, type, content) value ( ?, ?, ?, ?)'
    db.query(userInsertSql, [name, orderby, type, content], (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        };
        res.send({
            code: 0,
            message: '添加成功',
        })
    })
};


/**
 * 修改栏目接口
 */
exports.updateColumnListById = (req, res) => {
    let { id, name, orderby, type, content } = req.query;
    let sql = 'update cms_column set  name = ?, orderby = ?, type = ? , content = ? where id = ?'
    db.query(sql, [name, orderby, type, content, id], (err, results) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        res.send({ code: 0, message: '修改成功' });
    })
}

// 删除栏目接口
exports.deleteColumnListById = (req, res) => {
    let { id } = req.query;
    let sql = 'update cms_column set del = 1 where id = ?'
    db.query(sql, id, (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        res.send({ code: 0, message: '删除成功' })

    })
}